﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VDataAdapter;

namespace VDataAdapter.Communication
{
    /// <summary>
    /// This class checks if the flag sent to Vdata is in correct sequence
    /// i.e. BEGIN > END > END_RECOVERY
    /// </summary>
    class VdataFlagChecker
    {
        MessageFlagSequeue _currentFlag = MessageFlagSequeue.NULL; // not begin yet

        public VdataFlagChecker() { }

        public void CheckFlag(string msg)
        {
            MessageFlagSequeue flag = VDataFlag.GetFlag(msg);

            // if correct sequence or BEGIN flag received
            if (!isCorrectFlagSequence(flag, _currentFlag))
                throw new InvalidOperationException("Unknown Flag passed by or Invalid Flag Sequence");
            
            // pass validation, update current flag
            _currentFlag = flag;
        }

        private bool isCorrectFlagSequence(MessageFlagSequeue nextFlag, MessageFlagSequeue currentFlag)
        {
            //// begin after null
            if (nextFlag == MessageFlagSequeue.BEGIN && currentFlag == MessageFlagSequeue.NULL)
                return true;
            
            // end after begin
            if(nextFlag == MessageFlagSequeue.END && currentFlag == MessageFlagSequeue.BEGIN)
                return true;

            // end recovery after end
            if(nextFlag == MessageFlagSequeue.END_RECOVERY && currentFlag == MessageFlagSequeue.END)
                return true;
 
            return false;
        }
 
    }
}
